package io.gitee.mingbaobaba.security.quickstart.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.gitee.mingbaobaba.security.core.exception.SecurityBusinessException;
import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;

/**
 * <p> Ticket 工具</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/9/5 22:38
 */
public class TicketUtil {

    /**
     * 密钥
     */
    private static final String SECRET = "athena@#$^%&&^*(()()O2fgf";

    private TicketUtil() {

    }

    /**
     * 生成Ticket
     *
     * @param id ID
     * @return ticket
     */
    public static String generateTicket(String id) {
        Calendar instance = Calendar.getInstance();
        //默认令牌过期时间60秒
        instance.add(Calendar.SECOND, 60);

        JWTCreator.Builder builder = JWT.create();
        builder.withJWTId(id);
        return builder.withExpiresAt(instance.getTime())
                .sign(getAlgorithm());
    }

    /**
     * 生成Ticket
     *
     * @param id        id
     * @param expiresAt 过期时间 单位秒
     * @return ticket
     */
    public static String generateTicket(String id, Long expiresAt) {
        JWTCreator.Builder builder = JWT.create();
        Calendar instance = Calendar.getInstance();
        //默认令牌过期时间60秒
        instance.add(Calendar.SECOND, expiresAt.intValue());
        builder.withJWTId(id);
        return builder.withExpiresAt(instance.getTime())
                .sign(getAlgorithm());
    }


    /**
     * 验证ticket合法性
     *
     * @param ticket 票据
     * @return {@link DecodedJWT}
     */
    public static DecodedJWT verify(String ticket) {
        if (StringUtils.isEmpty(ticket)) {
            throw new SecurityBusinessException("ticket不能为空");
        }
        JWTVerifier build = JWT.require(getAlgorithm()).build();
        return build.verify(ticket);
    }

    /**
     * 解析ticket获取id
     *
     * @param ticket 票据
     * @return id
     */
    public static String parseTicket(String ticket) {
        return verify(ticket).getId();
    }

    @SuppressWarnings("all")
    private static Algorithm getAlgorithm() {
        return Algorithm.HMAC256(SECRET);
    }

}
